
import WxRequest from './request'
import { getStorage, clearStorage } from './storage'
import { modal, toast } from './extendApi'


// 实例化传参
const instance = new WxRequest({
  baseURL: 'https://gmall-prod.atguigu.cn/mall-api',
  timeout: 15000
})

// 请求拦截器
instance.interceptors.request = function (config) {
  const token = getStorage('token')

  if (token) {
    config.header['token'] = token
  }


  return config
}

// 响应拦截器
instance.interceptors.response = async function (response) {
  const { data, isSuccess } = response

  if (!isSuccess) {
    wx.showToast({
      title: '网络异常请重试',
      icon: 'error'
    })
    return response
  }

  switch (data.code) {
    case 200:
      
      return data
    case 208:
      const res = await modal({
        content: '鉴权失败，请重新登录',
        showCancel: false
      })

      if (res) {
        console.log('res', res)
        clearStorage()

        wx.navigateTo({
          url: "/pages/login/login",
        })
      }
      return Promise.reject(response)
      
    default:
      toast({
        title: '程序出现异常，请联系客服或重新尝试'
      })
      return Promise.reject(response)
  }

  
}

export default instance